/******************************************************************
 * Created by: GOH CHEE HONG                                      
 * Date of Creation: 1/Jan/2009     
 * Date of last modification: 
 *                                                                
 * Description: a network stream 
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
namespace Pbdms.NetworkDealer
{
    public class SmartNetworkStream
    {
        NetworkStream networkStream;
        public SmartNetworkStream()
        {

        }
        public SmartNetworkStream(TcpClient client)
        {
            this.networkStream= client.GetStream();
        }
        /// <summary>
        /// read bytes
        /// </summary>
        /// <returns></returns>
        public byte[] Read()
        {
            byte [] messageSize= new byte[4];

            //receive message size first
            int totalRecv = 0;
            while (totalRecv != 4)
            {
                int recv= networkStream.Read(messageSize,totalRecv,4-totalRecv);
                totalRecv+=recv;
                ///receive 0 data throw error
                if(recv==0)
                {
                    throw new Exception("no data");
                }
            }
            

            //calculate the size of the message
            int size = BitConverter.ToInt32(messageSize,0);
            //set the size of the message
            byte[] data = new byte[size];

        
            //read the message

            int totalReceived = 0;
            while (totalReceived != size)
            {
                int recv = networkStream.Read(data, totalReceived, size - totalReceived);
                totalReceived += recv;
                if (recv == 0)
                {
                    throw new Exception("no data");
                }
            }
            return data;
        }
        /// <summary>
        /// write bytes
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="size"></param>
        public void Write(byte[] buffer,int offset,int size)
        {
            //size of the message
            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(buffer.Length);
            //send the size first
            networkStream.Write(datasize, 0, 4);
            //send the message
            networkStream.Write(buffer,offset,buffer.Length);
        }
        public void Close()
        {
            this.networkStream.Close();
        }
    }
}
